<?php

namespace app\service;


class Predis
{
    public $redis = "";

    /**
     * 定义单例模式的变量
     * @var null
     */
    private static $_instance = [];

    public static function getInstance($select_db = 0)
    {
        if (!isset(self::$_instance[$select_db])) {
            self::$_instance[$select_db] = new self($select_db);
        }
        return self::$_instance[$select_db];
    }

    private function __construct($select_db)
    {
        $this->redis = new \Redis();
        $result = $this->redis->connect(env('redis.host'), env('redis.port'), 5);
        if (env('redis.auth')) {
            $this->redis->auth(env('redis.auth'));
        }
        if ($select_db) {
            $this->redis->select($select_db);
        }

        if ($result === false) {
            throw new \Exception('redis connect error');
        }
    }

    /**
     * set
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($key, $value, $time = 0)
    {
        if (!$key) {
            return false;
        }
        if (is_array($value)) {
            $value = json_encode($value);
        }
        if (!$time) {
            return $this->redis->set($key, $value);
        }

        return $this->redis->setex($key, $time, $value);
    }

    /**
     * @param $name
     * @param $arguments
     * @return bool
     */
    public function __call($name, $arguments)
    {
        //p($name, $arguments);
        /*if (is_array($arguments) && count($arguments) == 1) {
            return $this->redis->$name($arguments[0]);
        }
        if (is_array($arguments) && count($arguments) == 2) {
            return $this->redis->$name($arguments[0], $arguments[1]);
        }
        return false;*/
        try {
            return call_user_func_array([$this->redis, $name], $arguments);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }
}